package com.ruoyi.framework.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.login.api.ApiSessionHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Slf4j
public class BizMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        if (metaObject.hasGetter("createTime")) {
            if (metaObject.getValue("createTime") == null) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
        }

        // 有该字段则不自动填充以下字段
        if (!metaObject.hasGetter("noCanAutoField")) {
            if (metaObject.hasGetter("createBy")) {
                if (metaObject.getValue("createBy") == null) {
                    Long createBy = ApiSessionHolder.getSessionObjId();
                    if (createBy == null) {
                        LoginUser loginUser = SecurityUtils.getLoginUser();
                        createBy = loginUser != null ? loginUser.getUserId() : 0L;
                    }
                    this.setFieldValByName("createBy", createBy, metaObject);
                }
            }
            if (metaObject.hasGetter("delFlag")) {
                if (metaObject.getValue("delFlag") == null) {
                    this.setFieldValByName("delFlag", "0", metaObject);
                }
            }
        }

        if (metaObject.hasGetter("createByName")) {
            if (metaObject.getValue("createByName") == null) {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                this.setFieldValByName("createByName",
                        loginUser != null ? loginUser.getUsername() : "系统"
                        , metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        // 有该字段则不自动填充以下字段
        if (!metaObject.hasGetter("noCanAutoField")) {
            if (metaObject.hasGetter("disableUpdateByFill")) {
                if (metaObject.getValue("disableUpdateByFill") == null
                        || metaObject.getValue("disableUpdateByFill").equals(false)) {
                    Long updateBy = ApiSessionHolder.getSessionObjId();
                    if (updateBy == null) {
                        LoginUser loginUser = SecurityUtils.getLoginUser();
                        updateBy = loginUser != null ? loginUser.getUserId() : 0L;
                    }
                    this.setFieldValByName("updateBy", updateBy, metaObject);
                }
            }
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}
